﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;

namespace HCD.Web.MDC.Authorizer
{
    /// <summary>
    ///
    /// </summary>
    public class JWTUtil
    {
        //private static readonly string DEFAULT_SECURE_KEY = "Json_Web_Token_Default_Key";
        public static string key;
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="payload"></param>
        /// <returns></returns>
        public static string GenerateToken(AuthModel payload)
        {
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); //加密器

            var token = encoder.Encode(payload, key);
            return token;
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static AuthModel DecodeToken(string token)
        {
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);   //解密器

            var dic = decoder.DecodeToObject<AuthModel>(token, key, true);
            return dic;
        }
    }
}